package com.zxcl.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zxcl.domain.Category;
import com.zxcl.dto.CategoryUpdateDTO;
import com.zxcl.model.Result;

import com.zxcl.service.impl.CategoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 描述: [分类管理接口]
 * 作者: zxcl
 */
@RestController
@Api(tags = "分类管理接口")
@RequestMapping("prod/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 查询所有分类信息
     * id查询也存缓存
     * @return
     */
    @GetMapping("table")
    @ApiOperation("查询所有分类信息")
    @PreAuthorize("hasAuthority('prod:category:page')")
    public Result<List<Category>> loadCategories() {
        List<Category> categoryList = categoryService.loadCategories();
        return Result.success(categoryList);
    }


    @GetMapping("listCategory")
    @ApiOperation("查询可用所有父分类列表")
    @PreAuthorize("hasAuthority('prod:category:page')")
    public Result<List<Category>> loadParentCategories() {
        return Result.success(categoryService.loadParentCategories());
    }

    @PostMapping
    @ApiOperation("新增分类")
    @PreAuthorize("hasAuthority('prod:category:save')")
    public Result<String> addCategory(@RequestBody @Validated Category category) {
        Integer i = categoryService.addCategory(category);
        return Result.handle(i > 0);
    }


    @GetMapping("info/{userId}")
    @ApiOperation("获取当前分类信息")
    @PreAuthorize("hasAuthority('prod:category:info')")
    public Result<Category> loadMenu(@PathVariable Long userId){
        Category category = categoryService.getById(userId);
        return Result.success(category);
    }


    @PutMapping
    @ApiOperation("修改分类")
    @PreAuthorize("hasAuthority('prod:category:update')")
    public Result<String> updateCategory(@RequestBody @Validated CategoryUpdateDTO categoryUpdateDTO) {
        Integer i = categoryService.updateCategory(categoryUpdateDTO);
        return Result.handle(i > 0);
    }


    @DeleteMapping("/{userId}")
    @ApiOperation("删除分类")
    @PreAuthorize("hasAuthority('prod:category:delete')")
    public Result<String> deleteCategory(@PathVariable Long userId){

        UpdateWrapper<Category> categoryUpdateWrapper = new UpdateWrapper<>();
        categoryUpdateWrapper.eq("category_id",userId)
                        .set("status",0);
        boolean update = categoryService.update(null, categoryUpdateWrapper);
        return Result.handle(update);
    }



}
